'''
Created on Jan 17, 2011

@author: dexen
'''


import os
import time
import threading
import SimpleHTTPServer, BaseHTTPServer, httplib

from dexen.system.common import utils
from dexen.system.common.constants import ARCHIVE_ROOT_DIR, ARCHIVE_PORT, \
                                          TEMP_ROOT_DIR

#===============================================================================
# Custom Classes to make Http server stoppable
#===============================================================================
class StoppableHttpRequestHandler (SimpleHTTPServer.SimpleHTTPRequestHandler):
    """http request handler with QUIT stopping the server"""

    def do_QUIT (self):
        """send 200 OK response, and set server.stop to True"""
        self.send_response(200)
        self.end_headers()
        self.server.stop = True

class StoppableHttpServer (BaseHTTPServer.HTTPServer):
    """http server that reacts to self.stop flag"""

    def serve_forever (self):
        """Handle one request at a time until stopped."""
        self.stop = False
        while not self.stop:
            self.handle_request()

def stop_server (port):
    """send QUIT request to http server running on localhost:<port>"""
    conn = httplib.HTTPConnection("localhost:%d" % port)
    conn.request("QUIT", "/")
    conn.getresponse()
    
#===============================================================================
# 
#===============================================================================
def _create_archive_dir():
    if not os.path.exists(TEMP_ROOT_DIR):
        os.mkdir(TEMP_ROOT_DIR)
    os.mkdir(ARCHIVE_ROOT_DIR)

def _cleanup_archive_dir():
    if os.path.exists(ARCHIVE_ROOT_DIR):
        utils.rmentry(ARCHIVE_ROOT_DIR)

def _start_archive_server():
    _cleanup_archive_dir()
    _create_archive_dir()
    os.chdir(ARCHIVE_ROOT_DIR)
    httpd = StoppableHttpServer(("", ARCHIVE_PORT), StoppableHttpRequestHandler)
    httpd.serve_forever()
    
def start():
    t = threading.Thread(target=_start_archive_server)
    t.start()
    try:
        while True:
            time.sleep(2)
    except KeyboardInterrupt:
        stop_server(ARCHIVE_PORT)
        print "Dexen archive server is closed."
        

def main():
    start()

if __name__ == "__main__":
    main()
